#!/usr/bin/env python
#
# condense is used to put the entire wiki into a single file.
#
# This is a submodule of warbler (warbler.org)
#
# Copyright (c) 2008 by Patrick Maupin <pmaupin@gmail.com>

import os
import glob
from wiki_report import WikiInfo, stripnavigation

dstname = 'entire_wiki.txt'

ignore = 'SinglePageWarblerManual'.split()

toolsdir = os.path.dirname(__file__)
rootdir = os.path.abspath(os.path.join(toolsdir, '..'))
dstname = os.path.join(toolsdir, dstname)

prev = ''

if os.path.exists(dstname):
    f = open(dstname, 'rb')
    prev = f.read()
    f.close()
    prev = prev.split('\n.CatchAll', 1)
    if len(prev) == 1:
        prev = ''
    else:
        prev = '\n.CatchAll' + prev[-1]

    backups = [x.rsplit('.',1)[-1] for x in glob.glob(dstname+'.*')]
    backups = [int(x) for x in backups if x.isdigit()] + [0]
    os.rename(dstname, '%s.%03d' % (dstname, max(backups) + 1))

assert not os.path.exists(dstname)

def fnames():
    result = []
    pagedict = WikiInfo.fnames.copy()
    for fname in ignore:
        if fname in pagedict:
            del pagedict[fname]
    for fname in WikiInfo.pageorder:
        if fname in pagedict:
            result.append((fname, pagedict.pop(fname)))
    result.extend(sorted(pagedict.iteritems()))
    return result

result = []
fmt = '\n\n' + 78 * '-' + '\n\n.%s\n\n'
for fname, fullname in fnames():
    fdata = stripnavigation(fullname)
    assert '\n.' not in fdata
    result.append(fmt % fname)
    result.append(fdata)

result = ''.join(result)
for name in WikiInfo.singular:
    result = result.replace('[%ss %s]' % (name, name), name)

dstfile = open(dstname, 'wb')
dstfile.write(result)
dstfile.write(prev)
dstfile.close()
